package com.javabaas.server.novel_server.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class StringRedisService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取某个key的剩余过期时间
     *
     * @param key redis key
     */

    public long residualExpirationTime(String key) {
        return stringRedisTemplate.getExpire(key);
    }


    /**
     * 当key不存在时，为key赋值
     *
     * @param key redis key
     *
     * @param value redis value
     */
    public boolean setValue(String key, String value) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        return ops.setIfAbsent(key, value);
    }


    /**
     * 为key赋值，同时设置过期时间
     *
     * @param key redis key
     *
     * @param value redis value
     *
     * @param time expire time(second)
     */
    public void set(String key, String value, long time) {
        BoundValueOperations<String, String> ops = stringRedisTemplate.boundValueOps(key);
        ops.set(value, time, TimeUnit.SECONDS);
    }


    /**
     * 读取缓存
     *
     * @param key redis key
     */
    public String get(String key) {
        BoundValueOperations<String, String> ops = stringRedisTemplate.boundValueOps(key);
        return ops.get();
    }


    /**
     * 删除某个key
     *
     * @param key redis key
     */
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }



    /**
     * 判断某个key是否存在
     *
     * @param key redis key
     */
    public boolean exist(String key) {
        return stringRedisTemplate.hasKey(key);
    }



    /**
     * 同redis命令的leftpush
     *
     * @param key redis
     *
     * @param value redis value
     */
    public void leftPush(String key, String value) {
        stringRedisTemplate.boundListOps(key).leftPush(value);
    }




    /**
     * 同redis命令的rightpop
     *
     * @param key redis key
     */
    public String rightPop(String key) {
        return stringRedisTemplate.boundListOps(key).rightPop();
    }



}
